package me.qingji.zebra;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

public class Fetcher {

	private HttpClient httpclient = new DefaultHttpClient();
	private String contentType = "text/html; charset=UTF-8";
	private String charset = "UTF-8";

	public String doGet(String url) {
		HttpClient httpclient = new DefaultHttpClient();
		HttpGet httpget = new HttpGet(url);
		httpget.setHeader("Content-Type", contentType);
		try {
			HttpResponse response = httpclient.execute(httpget);
			return getContent(response);
		} catch (IOException e) {
			throw new RuntimeException(e);
		} finally {
			httpget.abort();
		}
	}

	String streamToString(InputStream is) throws IOException {
		byte[] buf = new byte[4096];
		StringBuilder content = new StringBuilder();
		while ((is.read(buf)) != -1) {
			content.append(new String(buf, Charset.forName(charset)));
		}
		return content.toString();
	}

	String getContent(HttpResponse response) throws IllegalStateException,
			IOException {
		HttpEntity entity = response.getEntity();

		InputStream is = entity.getContent();
		String content = streamToString(is);
		return content;
	}

	public void shutdown() {
		httpclient.getConnectionManager().shutdown();
	}
	
	public void setContentType(String contentType) {
		this.contentType = contentType;
	}
	public String getContentType() {
		return contentType;
	}
	
	public void setCharset(String charset) {
		this.charset = charset;
	}
	public String getCharset() {
		return charset;
	}
}
